<template>
  <div class="imageUpload">
    <uni-file-picker limit="2" file-extname="png,jpg,jpeg,mp4,mp3,ppt,pptx,doc,docx,xls,xlsx" v-model="imageValue" mode="grid"
      :file-mediatype="fileType == 'file' ? 'all' : 'video' " :sourceType="fileType == 'file' ? ['album', 'camera'] : ['camera'] "  @select="select" @progress="progress" @success="success"
      @fail="fail" :del-icon="true">
    </uni-file-picker>
  </div>
</template>

<script>
import { baseUrl } from "@/config"; // 默认路径
import { getToken } from '@/utils/auth'
export default {
  props: {
    value: {
      default: "",
    },
    // 上传张数
    fileType: {
      default: "file",
    },
  },
  // props: ["value"],
  data() {
    return {
      imageValue: [],
    };
  },
  watch: {
    value: {
      handler(val, oval) {
        if (val && val != oval) {
          this.imageValue = [];
          let arr = val.split(",");
          if (arr) {
            arr.forEach((item) => {
              let name = item.split("/").pop();
              let extname = name.split(".")[1];
              this.imageValue.push({
                url: item,
                name,
                extname,
              });
            });
          }
        }
      },
      deep: true, //是否深度监听
      immediate: true, //是否监听初始
    },
    imageValue: {
      handler(val, oval) {
        if (val.length > 0) {
          let arr = [];
          val.forEach((item) => {
            arr.push(item.url);
          });
          const str = arr.join(",");
          this.$emit("input", str);
        } else {
          this.$emit("input", "");
        }
      },
      deep: true, //是否深度监听
      immediate: true, //是否监听初始
    },
  },
  methods: {
    updata(filePath, fileName) {
      console.log(filePath, "filePath");
      const that = this;
      const accessToken = getToken() || null; //获取token
      uni.uploadFile({
        url: baseUrl + "/v1/files",
        filePath,
        name: 'file',
        header: {
          Authorization: `Bearer ${accessToken}`,
        },
        formData: {
          fileName: fileName
        },
        success(res) {
          let response = JSON.parse(res.data);
          // console.log("=======上传文件完成======>", response);


          // console.log("=======response.data.url======>", response.data);
          if (response.data != undefined) {
            let str;

            if (that.value) {
              str = that.value + "," + response.data.url;
            } else {
              str = response.data.url;
            }
            console.log(str, "上传文件成功");
            that.$emit("input", str);
            uni.showToast({
              title: "上传文件成功",
              duration: 2000,
            });
          } else {
            uni.showToast({
              title: "上传文件失败,请重试!",
              icon: "none",
              duration: 2000,
            });
          }
        },
        fail(err) {
          // console.log("=======上传文件失败======>", err);
          uni.showToast({
            title: "上传文件失败,请重试!",
            icon: "none",
            duration: 2000,
          });
        },
        complete() {
          // if (isLoading) wx.hideLoading()
        },
      });
    },
    // 获取上传状态
    select(e) {
          e.tempFiles.forEach((item, i) => {
            if (item.size > 100 * 1024 * 1024) {
              uni.showToast({
                title: '图片大小超过100M，请重新选择照片',
                icon: 'none'
              })
              this.$refs.fileUpload.clearFiles()
            } else {
              this.updata(item.path, item.name);
            }
    
          });
        },
    // 获取上传进度
    progress(e) {
      console.log("上传进度：", e);
    },

    // 上传成功
    success(e) {
      console.log("上传成功");
    },

    // 上传失败
    fail(e) {
      console.log("上传失败：", e);
    },
  },
  onLoad(options) {
    // let arr = this.value.split(',')
    // console.log(arr)
    // arr.forEach((item) => {
    //   this.imageValue.push({
    //     url: baseUrl + item,
    //   })
    // })
  },
};
</script>

<style lang="scss" scoped></style>
